package luweiteng.demoForLogin.controller;

import luweiteng.demoForLogin.entity.TestUser;
import luweiteng.demoForLogin.shiro.realm.ConsumerRealm;
import luweiteng.demoForLogin.vo.req.TestUserReq;
import luweiteng.demoForLogin.vo.resp.BaseResp;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping(value = "/pc")
public class LoginController {

    @Autowired
   private ConsumerRealm consumerRealm;

    @RequestMapping(value = "/login" ,method = RequestMethod.POST)
    public BaseResp login(@RequestBody TestUser user , HttpServletResponse response){
        UsernamePasswordToken token =  new UsernamePasswordToken(user.getUserName(),user.getPassword());



        SecurityManager manager = new DefaultSecurityManager(consumerRealm);
        SecurityUtils.setSecurityManager(manager);

        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        TestUserReq userReq = new TestUserReq();
        BeanUtils.copyProperties(user,userReq);

//        这个位置的Token 就是 Cookies 中的 value
        String tokenKey = response.getHeader("x-auth-token");
        userReq.setPassword(null);
        userReq.setToken(tokenKey);

        return  BaseResp.success(userReq);
    }

}
